import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
  RouteRecordRaw,
} from "vue-router";
import { App } from "vue";
import Cookies from "js-cookie";
import store from "../store";

const routes: RouteRecordRaw[] = [
  // 路由规则：只有用户登录了，才能去访问别的路由页面
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

const getRoutes = (to: { path: string }, from: {}, next: ({}) => void) => {
  store.dispatch("getMenus").then((res) => {
    const menus = store.getters.getNewMenus;

    for (const key in menus) {
      const newRoute: RouteRecordRaw = {
        path: "/" + menus[key].name,
        name: menus[key].name,
        component: () => import("../views/index.vue"),
        redirect: "/" + menus[key].name + "/" + menus[key].children[0].name,
        //只输入一级菜单的path，默认跳转到一级菜单下的**第一个**二级菜单页面
        children: [],
      };
      for (let i = 0; i < menus[key].children.length; i++) {
        newRoute.children?.push({
          path: menus[key].children[i].name,
          name: menus[key].children[i].name,
          component: () =>
            import(
              `../views/${menus[key].name}/${menus[key].children[i].name}.vue`
            ),
        });
      }
      // 动态添加路由规则
      router.addRoute(newRoute);
    }
    router.addRoute({
      path: "/index",
      name: "index",
      redirect: "/home",
      component: () => import("../views/index.vue"),
      children: [
        {
          path: "/home",
          name: "home",
          component: () => import("../views/home/home.vue"),
        },
      ],
    });
    router.addRoute({
      path: "/",
      redirect: "/home",
    });
    return next(to);
  });
};

// 前置导航守卫
router.beforeEach((to, from, next) => {
  const token = Cookies.get("token");
  if (token && store.state.menus.length === 0) {
    getRoutes(to, from, next);
  } else if (token && to.path === "/index" && from.path === "/login") {
    // 第一次从login跳转到index
    getRoutes(to, from, next);
  } else if (!token && to.path !== "/login") {
    // 检查是否有token，没有则去登录页
    return next("/login");
  } else if (token && to.path === "/login") {
    next(from.path);
  }else {
    next();
  }
});

export const initRouter = (app: App<Element>) => {
  app.use(router);
};
